<template>
  <div class="superBox">
    <div class="superMain mgt-30 max_w-1200">
      <div style="width:100%" class="mgb-20">
        <Title></Title>
      </div>
      <div class="flex-s-between">
        <div style="width:45%" v-if="JSON.stringify(infoData) !== '{}'">
          <!-- <info :showDesc="showDesc" :from="fromPage" :makerOrder="makerOrder" :infoData="infoData" /> -->
          <div>
            <art-info :infoData="infoData"></art-info>
          </div>
          <div class="border-r bg-47 border-1 mgt-10 boxS-i-4">
            <div v-if="isSell" class="font-26 fontW-7 font-f-ib color-af47 bd-b-1 pdtb-10">
              <interval :date="countdownData"/>
            </div>
            <!-- 特点 -->
            <div class="flex mg-2">
              <div class="flex-1">
                <div class="color-af47 font-14 fontW-7 font-f-ib">{{ $t("detail.trait")}}</div>
                <p class="font-14 fontW-4 font-f-ib color-f mgt-10"
                    v-for="(item, i) in characteristic" :key="i">{{ item.trait_type }}
                    <span class="mgl-13">{{item.value}}</span></p>
                <!-- <div>
                  <div class="font-14 fontW-4 font-f-ib color-f mgt-10"
                    v-for="(item, i) in decoded" :key="i">
                    <div>{{ item.trait_type }}</div>
                    <div class="mgl-13">{{item.value}}</div>
                  </div>
                </div> -->
              </div>
              <!-- <div class="flex-1">
                <span class="color-af47 font-14 font-f-ib fontW-7">{{$t("detail.grade")}}</span>
                <p class="font-14 fontW-4 font-f-ib color-f mgt-10">{{ $t("detail.super") }}<span class="mgl-13">23/100</span></p>
                <p class="font-14 fontW-4 font-f-ib color-f mgt-10">{{ $t("detail.Motivation") }}<span class="mgl-13">11/100</span></p>
              </div> -->
            </div>
          </div>
          <div>
            <!-- 描述 -->
            <div class="border-r bg-47 border-1 mgt-10 boxS-i-4 pd-20" style="min-height:140px">
              <p class="color-af47 fontW-7 font-20 font-f-ib">{{ $t("detail.describe") }}</p>
              <div class="describe_p  color-f fontW-7 font-18 mg-10 font-f-ib" >{{description}}</div>
            </div>
          </div>
        </div>
        <div class="rightBox" style="width:42%">
          <div class="imgItem border-1 border-r pd-20 center_a">
            <img class="bd-r-10" :src="infoData.image_url" alt="" />
          </div>
          <div class="flex-s-between ">
            <div style="width:45%">
              <div class="font-20 fontW-7 color-f text-c" style="margin-top:16px">{{$t('buypage.price')}}</div>
              <div class="border-3 color-f border-r font-20 fontW-7 text-r h-3">
                {{sellPrice}}
                <img style="width:20px;margin-bottom:5px" class="mgr-10" src="../../assets/ETH/ETH.svg" alt="">
              </div>
              <div class="text-r font-14 fontW-7 color-a" >
                1600000
                <img src="../../assets/icon/dollar.svg" style="margin:0 5px 2px 2px" alt="">
              </div>
            </div>
            <div style="width:45%">
              <div class="font-20 fontW-7 color-ffc4 text-c">{{$t('buypage.group')}}</div>
              <div class="border-3-f6c4 color-f border-r font-20 fontW-7 text-r h-3">
                283.32
                <img style="width:20px;margin-bottom:5px" class="mgr-10" src="../../assets/ETH/IMEETNFT.svg" alt="">
              </div>
              <div class="text-r font-14 fontW-7 color-a"></div>
            </div>
          </div>
          <div>
            <div class="btn flex-s-between">
              <el-button type="primary" class="bg-af47 color-0 font-f-ib font-26 fontW-7 btnHove" @click="buyArtWork">{{ $t("buypage.snapUp") }}</el-button>
              <el-button type="primary" class="bg-ffc4 color-0 font-f-ib font-26 fontW-7 btnHove" @click="centerDialogVisible">{{ $t("buypage.openGroup") }}</el-button>
            </div>
          </div>
        </div>
      </div>
      <agent :brokerData="brokerData"/>
      <p class="font-25 fontW-7 font-f-ib color-af47 mgl-30">{{$t('title.history_bids')}}</p>
      <offer :offerData="offerData"/>
      <p class="font-25 fontW-7 font-f-ib color-af47 mgl-30">{{$t('title.vitality')}}</p>
      <activity :activityData="activityData"/>
      <!-- <opengroup v-if="centerVisible" @oncenSHow="oncenSHow"/> -->
      <open-group-new v-if="centerVisible" @oncenSHow="oncenSHow"/>
      <!-- <open-group-new/> -->
      <join :joinData="joinData" />
    </div>
  </div>
</template>
<script>
import {initContract, initWeb3} from '../../../static/contract/createContract'
import contractAddress from '../../../static/contract/contractAddress'
import Info from '../../components/component/Info'
import ArtInfo from '../../components/component/ArtInfo'
import Interval from '../../components/component/Interval'
import Offer from '../../components/component/Offer'
import Activity from '../../components/component/Activity'
import Title from '../../components/component/Title'
import Agent from '../../components/component/Agent'
import Opengroup from '../../components/component/Opengroup'
import Join from '../../components/component/Join'
import OpenGroupNew from './components/OpenGroup'
import { offerData, activityData, brokerData, joinData } from '../../mock/data'

export default {
  components: {
    Info,
    ArtInfo,
    Interval,
    Offer,
    Activity,
    Title,
    Agent,
    Opengroup,
    OpenGroupNew,
    Join
  },
  data () {
    return {
      showDesc: true,
      offerData: offerData,
      activityData: activityData,
      infoData: {},
      brokerData: brokerData,
      joinData: joinData,
      centerVisible: false,
      fromPage: 'buyArt',
      web3: null,
      makerOrder: {},
      sellPrice: 0,
      ImeetERC20Contract: null,
      takerOrder: null,
      ImeetExchangeContract: null,
      strategy: '',
      countdownData: 0, // 倒计时
      ownerFlag: false, // 是否是拥有者
      isSell: false, // 是否已经挂售
      ZERO_ADDRESS: '0x0000000000000000000000000000000000000000'
    }
  },
  created () {
    this.web3 = initWeb3()
    let contractObj = initContract()
    console.log(contractObj, this.web3, contractAddress) // 合约初始化
    this.ImeetERC20Contract = contractObj.ImeetERC20Contract
    this.ImeetExchangeContract = contractObj.ImeetExchangeContract
    console.log(this.ImeetERC20Contract)
    this.getDetails()
  },
  methods: {
    centerDialogVisible: function () {
      this.centerVisible = true
    },
    oncenSHow: function (val) {
      this.centerVisible = val
    },
    /**
     * 查询艺术品详情
     * @param {id} 艺术品ID
    */
    getDetails: function () {
      this.$loading.show()
      const params = {
        // collectionAddress: this.$route.query.CollectionAddress,
        id: this.$route.query.artId
      }
      this.$Api.Collection.getCollectionArtDetail(params)
        .then((res) => {
          this.$loading.hide()
          // console.log(res, 'getDetails', JSON.stringify(res))
          if (res && res.code === 200) {
            this.infoData = res.data.asset
            if (this.infoData.HoldAddress === this.$cookies.get('wallet_acount')) {
              this.ownerFlag = true
            } else {
              this.ownerFlag = false
            }
            if (res.data.makerOrder.ID === 0) {
              this.isSell = false
            } else {
              this.isSell = true
            }
            const decoded = decodeURI(atob(this.infoData.Metadata))
            this.characteristic = JSON.parse(decoded)
            this.description = this.infoData.Description
            this.countdownData = res.data.makerOrder.EndTime
            // this.makerOrder = res.data.makerOrder
            this.makerOrder = {
              isOrderAsk: res.data.makerOrder.IsOrderAsk,
              signer: res.data.makerOrder.Signer,
              collection: res.data.makerOrder.CollectionAddress,
              price: res.data.makerOrder.Price,
              tokenId: Number(res.data.makerOrder.TokenId),
              amount: res.data.makerOrder.Amount,
              strategy: res.data.makerOrder.StrategyAddress,
              currency: res.data.makerOrder.CurrencyAddress,
              nonce: res.data.makerOrder.Nonce,
              startTime: res.data.makerOrder.StartTime,
              endTime: res.data.makerOrder.EndTime,
              minPercentageToAsk: res.data.makerOrder.MinPercentageToAsk,
              params: res.data.makerOrder.Params,
              signature: res.data.makerOrder.Signature
            }
            this.sellPrice = res.data.makerOrder.Price
            // console.log(this.infoData, res.data)
          }
        })
        .catch((err) => {
          this.$loading.hide()
          console.log(err, 'getDetails', JSON.stringify(err))
        })
    },
    buyArtWork: function () {
      this.ApproveSubmit()
    },
    ApproveSubmit: async function() {
      console.log(contractAddress.ImeetExchangeAddress)
      await this.ImeetERC20Contract.methods
        .approve(contractAddress.ImeetExchangeAddress, this.web3.utils.toWei('10000', 'ether'))
        .send({from: this.$cookies.get('wallet_acount')}, (err, res) => {
          console.log(err, res, 'approve')
          if (res) {
            this.submitSign()
          } else {
            console.log('approve.err:' + err)
          }
        })
    },
    submitSign: function () {
      const from = this.$cookies.get('wallet_acount')
      const price = this.makerOrder.price + ''
      var paramsTaker = new Uint8Array(1)
      paramsTaker[0] = 0x32 // 0x32:2, 0x31:1
      this.takerOrder = {
        isOrderAsk: 0,
        taker: this.$cookies.get('wallet_acount'),
        price: this.web3.utils.toWei(price, 'ether'),
        tokenId: this.makerOrder.tokenId,
        minPercentageToAsk: 9000,
        params: paramsTaker
      }
      this.makerOrder.price = this.web3.utils.toWei(this.makerOrder.price + '', 'ether')
      console.log(this.takerOrder, this.makerOrder)
      this.ImeetExchangeContract.methods.matchAskWithTakerBid(this.takerOrder, this.makerOrder)
        .send({from: from}, (error, transactionHash) => {
          console.log(error, transactionHash)
          if (transactionHash) {
            this.updateOwner()
          }
        })
    },
    // 更新个人作品信息
    updateOwner: function () {
      this.$loading.show()
      let data = new FormData()
      data.append('id', this.$route.query.artId)
      data.append('address', this.$cookies.get('wallet_acount'))
      const params = {
        data,
        headers: {
          'content-type': 'multipart/form-data'
        }
      }
      this.$Api.Order.updateOwnerInfo(params)
        .then(res => {
          this.$loading.hide()
          console.log(res)
          this.$router.push({
            path: '/person_collection',
            query: {
              type: 1
            }
          })
        })
        .catch(err => {
          this.$loading.hide()
          console.log(err, JSON.stringify(err))
        })
    }
  }
}
</script>
<style lang="less" scoped>
.superBox {
  width: 100%;
  height: auto;
  overflow: hidden;
  .superMain {
    width: 80%;
    height: auto;
    overflow: hidden;
    padding-bottom: 100px;
    .describe_p {
      height:100px;
      overflow-y: scroll;
      word-break: normal;
      white-space: pre-wrap;
      word-wrap:break-word;
    }
    p{
      margin-top: 20px;
    }
    .imgItem {
      img {
        width: 100%;
      }
    }
     .btn{
      margin-top: 9%;
    }
    .btn {
      /deep/.el-button--primary:nth-child(1) {
        background: #A0F4F7;
      }
      /deep/.el-button--primary:nth-child(2) {
        background: #fe66c4;
      }
      /deep/.el-button--primary {
        width: 45%;
        border: 0;
      }
      /deep/.el-button--primary:focus,
      .el-button--primary:hover {
        color: #fff;
        border: 0;
      }
    }
  }
}
</style>
